<!--
 * @Description: pdf生成导出
 * @Date: 2022-05-20 10:59:47
 * @LastEditTime: 2022-05-23 11:30:27
 * @FilePath: /demo_important/src/views/PdfExport/index.vue
 * @Author: softbank126010077018.bbtec.net
-->
<template>
  <div class="pdf-exports">
    <div id="pdfDom" style="padding: 10px">
      <div class="rows">
        <el-table :data="tableData" border>
          <el-table-column
            prop="date"
            label="日期"
            width="250"
          ></el-table-column>
          <el-table-column
            prop="name"
            label="姓名"
            width="250"
          ></el-table-column>
          <el-table-column prop="address" label="地址"></el-table-column>
        </el-table>
        <el-table :data="tableData" border>
          <el-table-column
            prop="date"
            label="日期"
            width="250"
          ></el-table-column>
          <el-table-column
            prop="name"
            label="姓名"
            width="250"
          ></el-table-column>
          <el-table-column prop="address" label="地址"></el-table-column>
        </el-table>
      </div>
      <div class="rows">
        <h1 class="row1">猴子1</h1>
        <img src="./images/猴子.webp" alt="" />
      </div>
      <div class="rows">
        <h1 class="row1">猴子2</h1>
        <img src="./images/猴子.webp" alt="" />
      </div>
    </div>

    <el-button type="button" style="margin-top: 20px" @click="btnClick">
      导出PDF1
    </el-button>
    <el-button
      type="button"
      style="margin-top: 20px"
      @click="getPdfFromHtml('pdfDom', '测试')"
    >
      导出PDF2
    </el-button>
  </div>
</template>

<script>
import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';
export default {
  name: 'PdfExport',
  components: {},
  props: {},
  data() {
    return {
      exportPDFtitle: '测试文件',
      tableData: [
        {
          date: '2016-05-06',
          name: '王小虎',
          address: '重庆市九龙坡区火炬大道',
        },
        {
          date: '2016-05-07',
          name: '王小虎',
          address: '重庆市九龙坡区火炬大道',
        },
        {
          date: '2016-05-03',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄',
        },
        {
          date: '2016-05-02',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄',
        },
        {
          date: '2016-05-04',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄',
        },
        {
          date: '2016-05-01',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄',
        },
        {
          date: '2016-05-08',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄',
        },
        {
          date: '2016-05-08',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄',
        },
        {
          date: '2016-05-08',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄',
        },
        {
          date: '2016-05-08',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄',
        },
        {
          date: '2016-05-08',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄',
        },
        {
          date: '2016-05-08',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄',
        },
      ],
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    // let targetPage = pdf.internal.getNumberOfPages(); //获取总页
    // pdf.deletePage(targetPage); // 删除目标页
    btnClick() {
      this.$nextTick(() => {
        // this.getPdf();
      });
    },
    getPdfFromHtml(ele, pdfFileName, hide) {
      // this.$message.loading('正在下载', 2.5)
      ele = document.getElementById('pdfDom');
      pdfFileName = pdfFileName || 'pdf';
      window.pageYoffset = 0; // 滚动置顶
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
      // ele.style.fontSize = '18px'
      // ele.style.padding='30px';
      // let scale = window.devicePixelRatio * 2
      html2Canvas(ele, {
        // dpi: 300,
        dpi: window.devicePixelRatio * 4, // 将分辨率提高到特定的DPI 提高四倍
        scale: 4, // 按比例增加分辨率
        // logging: false,
        // scale:scale,
        useCORS: true, // 允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
        // allowTaint: false,
        // height: ele.offsetHeight,
        // width: ele.offsetWidth,
        windowWidth: document.body.scrollWidth,
        windowHeight: document.body.scrollHeight,
        // backgroundColor: '#fff'
      }).then((canvas) => {
        // const _this = this
        // 未生成pdf的html页面高度
        let leftHeight = canvas.height;
        const a4Width = 555.28; // 原A4宽 592 因为要设置边距 20 ,这里要减掉 40
        const a4Height = 801.89; // 原A4高   841 因为要设置边距 20 ,这里要减掉 40
        // 一页pdf显示html页面生成的canvas高度;
        const a4HeightRef = Math.floor((canvas.width / a4Width) * a4Height);
        console.log("一页-------->",leftHeight);
        // pdf页面偏移
        let position = 0;

        const pageData = canvas.toDataURL('image/jpeg', 1.0);

        const pdf = new JsPDF('x', 'pt', 'a4');
        // let printIndex = 1
        const canvas1 = document.createElement('canvas');
        let height;
        pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen');

        function createImpl(canvas) {
          if (leftHeight > 0) {
            // printIndex++
            let checkCount = 0;
            if (leftHeight > a4HeightRef) {
              let i = position + a4HeightRef;
              for (i = position + a4HeightRef; i >= position; i--) {
                let isWrite = true;
                for (let j = 0; j < canvas.width; j++) {
                  const c = canvas
                    .getContext('2d')
                    .getImageData(j, i, 1, 1).data;

                  if (c[0] !== 0xff || c[1] !== 0xff || c[2] !== 0xff) {
                    isWrite = false;
                    break;
                  }
                }
                if (isWrite) {
                  checkCount++;
                  if (checkCount >= 10) {
                    break;
                  }
                } else {
                  checkCount = 0;
                }
              }
              height =
                Math.round(i - position) || Math.min(leftHeight, a4HeightRef);
              if (height <= 0) {
                height = a4HeightRef;
              }
            } else {
              height = leftHeight;
            }

            canvas1.width = canvas.width;
            canvas1.height = height;
            console.log( canvas1.width,canvas1.height);
            // console.log(index, 'height:', height, 'pos', position);

            const ctx = canvas1.getContext('2d');
            ctx.drawImage(
              canvas,
              0,
              position,
              canvas.width,
              height,
              0,
              0,
              canvas.width,
              height,
            ); // 边距这里设置0，不然又黑边

            // let pageHeight = Math.round(a4Width / canvas.width * height)
            // pdf.setPageSize(null, pageHeight)
            if (position !== 0) {
              pdf.addPage();
            }
            // 设置 20px 边距
            pdf.addImage(
              canvas1.toDataURL('image/jpeg', 1.0),
              'JPEG',
              20,
              20,
              a4Width,
              (a4Width / canvas1.width) * height,
            );
            leftHeight -= height;
            position += height;
            if (leftHeight > 0) {
              // 添加全屏水印
              /* const base64 = ''
              for (let i=0;i<6;i++) {
                for (let j=0;j<5;j++) {
                  const  left = (j * 120) + 20
                  pdf.addImage(base64,'JPEG', left, i*150, 20, 30); // 关掉水印
                }
              } */
              setTimeout(createImpl, 500, canvas);
            } else {
              pdf.save(pdfFileName + '.pdf');
              setTimeout(hide, 500);
              // this.$message.success('下载完成', 2.5)
            }
          }
        }

        // 当内容未超过pdf一页显示的范围，无需分页
        if (leftHeight < a4HeightRef) {
          pdf.addImage(
            pageData,
            'JPEG',
            20,
            20,
            a4Width,
            (a4Width / canvas.width) * leftHeight,
          );
          pdf.save(pdfFileName + '.pdf');
        } else {
          try {
            pdf.deletePage(0);
            setTimeout(createImpl, 500, canvas);
          } catch (err) {
            console.log(err);
          }
        }
      });
    },
  },
};
</script>

<style scoped >
.pdf-exports {
  width: 100%;
  height: 100%;
}
.rows {
  /* width: 555.28px; */
  height: 1080px;
}
.row1 {
  margin-bottom: 200px;
}
</style>
